<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js函数之递归函数</title>
</head>
<body>
  <ul>
    <li>递归函数即不断重复调用自身，直到有返回结果为止</li>
    <li>递归函数类似入栈，出栈，当递归开始时会依次将每一次递归表达式入栈，当有返回结果时依次将结果传递到上一层表达式出栈</li>
  </ul>
  <script>
    // 阶乘
    const factorial = function(num) {
      // if (num === 1) return 1
      // return num * factorial(num - 1)
      return num === 1 ? 1 : num * factorial(num - 1)
    }
    console.log(factorial(5))        // 120
    // 求和
    const sum = function(...args) {
      // if (!args.length) return 0
      // return args.pop() + sum(...args)
      return !args.length ? 0 : args.pop() + sum(...args)
    }
    console.log(sum(1, 2, 3, 4, 5))  // 15
    // 倒三角
    const star = function(num) {
      return num ? document.write(`${'*'.repeat(num)}<br/>`) || star(--num) : ''
    }
    star(5)
    // 数组map
    const map = function(arr, num = 100, i = 0) {
      if (i === arr.length) return arr
      arr[i].count += num
      return map(arr, num, ++i)
    }
    console.log(map([{
      name: 'JS', count: 10
    }, {
      name: 'ES', count: 25
    }, {
      name: 'TS', count: 30
    }]))
  </script>
</body>
</html>